﻿const express = require('express');
const router = express.Router();
const fs = require("fs");
const multer = require('multer');
const moment = require('moment');
const http = require('http');
const ClassModel = require('../models/class');
const createGuid = require('../lib/util').createGuid;
const dateToString = require('../lib/util').dateToString;
const ScoreSegmentModel = require('../models/score-segment');
const ScoreSubItemModel = require('../models/score-sub-item');
const get_client_ip = require('../lib/util').get_client_ip;


const upload = multer({ dest: './public/cover' });
const upload2 = multer({ dest: './public/img' });
// 根据老师的guid获取他的班级列表 GET /class/getClassList/:CreatorGuid?Overdue=&Stat
router.get('/getClassList/:CreatorGuid', function(req, res, next) {
    let CreatorGuid = req.params.CreatorGuid;
    let Valid = req.query.Valid || 1;
    let State = req.query.State || 0;
    ClassModel.getClassList(CreatorGuid, State, function(status, vals) {
        if (status == 1) {
            let selectTime = moment().format('YYYY-MM-DD').toString();
            let data = []
            if (Valid == 1) {
                data = vals
            } else {
                if (Valid == 99) {
                    for (let i = 0; i < vals.length; i++) {
                        if ((new Date(vals[i].EndTime.replace(/-/g, "\/"))) < (new Date(selectTime.replace(/-/g, "\/")))) {
                            data.push(vals[i])
                        }
                    }
                } else {
                    for (let j = 0; j < vals.length; j++) {
                        if ((new Date(vals[j].EndTime.replace(/-/g, "\/"))) >= (new Date(selectTime.replace(/-/g, "\/")))) {

                            data.push(vals[j])
                        }
                    }
                }
            }
            res.send({ status: status, data: data });
        } else {
            res.send({ status: status, err: vals });
        }

    });
});

router.get('/defaultCover', function(req, res, next) {
    res.send({
            status: 1,
            data: ['/IMG/Roster/Roster/cover/HistoricalData/defalut1.jpg',
                '/IMG/Roster/Roster/cover/HistoricalData/defalut2.png',
                '/IMG/Roster/Roster/cover/HistoricalData/defalut3.jpg',
                '/IMG/Roster/Roster/cover/HistoricalData/defalut4.jpg'
            ]
        })


})

// 删除或恢复班级 put class/:guid
router.put('/:guid', function(req, res, next) {
    let classGuid = req.params.guid;
    ClassModel.delClass(classGuid, req.body.State, function(status, vals) {
        if (status) res.send({ status: status, data: 'ok' });
        else res.send({ status: status, err: vals });
    });
});

// 上传封面 POST class/cover
router.post('/cover', upload.single('uploadimg'), function(req, res, next) {
    let imgName = createGuid();
    let suffix = req.file.originalname.split('.')[1];
    let path = `/cover/class/${imgName}.${suffix}`;
    fs.rename(req.file.path, `public/${path}`, function(err) {
        if (err) {
            console.log(err);
            res.send({ status: 0, err: err });
            return;
        }
        res.send({ status: 1, data: 'http://lppclass.arktao.com' + path });
    })
});
// 上传富文本图片 POST class/cover
router.post('/img', upload2.single('uploadimg'), function(req, res, next) {
    let imgName = createGuid();
    let suffix = req.file.originalname.split('.')[1];
    let path = `/img/class/${imgName}.${suffix}`;
    fs.rename(req.file.path, `public/${path}`, function(err) {
        if (err) {
            console.log(err);
            res.send({ status: 0, err: err });
            return;
        }
        res.send('http://lppclass.arktao.com' + path);
    })
});
// 添加班级 POST class
router.post('/addclass', function(req, res, next) {
    function createCode() {
        let numberString = '';
        for (let i = 0; i < 6; i++) {
            let n = Math.floor(Math.random() * 10);
            numberString += n;
        }
        return numberString;
    }
    let data = {
        className: req.body.className,
        
        endTime: req.body.endTime,
        creatorGuid: req.body.creatorGuid,
        coverUrl: req.body.coverUrl,
        idCode: createCode()
    };
    ClassModel.addClass(data, function(statusAddClass, valsAddClass) {
        if (statusAddClass) {
            let ip = get_client_ip();
            let classGuid = valsAddClass;
            ScoreSegmentModel.initClassScoreSegment(classGuid, ip, function(statusInitClassScoreSegment, valsInitClassScoreSegment) {
                if (statusInitClassScoreSegment)
                {
                    ScoreSubItemModel.initClassScoreSubItem(classGuid, ip, function(statusInitClassScoreSubItem, valsInitClassScoreSubItem) {
                        if (statusInitClassScoreSubItem)
                        {
                            res.send({ status: 1, data: valsInitClassScoreSubItem ,guid:classGuid});
                        }
                        else
                        {
                            res.send({ status:0, error: valsInitClassScoreSubItem });
                        }
                    });
                }
                else
                {
                    res.send({ status:0, error: valsInitClassScoreSegment });
                }
            });
        }
        else res.send({ status: statusAddClass, err: valsAddClass });
    });
});

// 编辑班级 Put class
router.post('/putclass', function(req, res, next) {
    console.log(1)
    let data = {
        PK_ClassGuid: req.body.PK_ClassGuid,
        className: req.body.className,
       
        endTime: req.body.endTime,
        coverUrl: req.body.coverUrl
    };
    console.log(data)
    console.log(1)
    ClassModel.putClass(data, function(status, vals) {
        if (status) res.send({ status: status, data: vals });
        else res.send({ status: status, err: vals });
    });
});


// 获取指定GUID班级 class/private/classListString=xxx
router.get('/private', function(req, res, next) {
    let classListString = req.query.classListString;
    let now = dateToString(new Date);
    ClassModel.getClassesByGuid(classListString, function(status, vals) {
        if (status) {
            let classList = vals.map(function(x) {
                if (x.EndTime > now) return x.State = 0;
                if (x.EndTime <= now) return x.State = 1;
            });
            res.send({ status: status, data: vals });
        } else res.send({ status: status, err: vals });
    });
});

// 获取当前所有可用班级列表 GET class/all
router.get('/all', function(req, res, next) {

    let data = {
        Valid: req.query.Valid || 1
    };
    console.log(data)
    ClassModel.getAllClasses(data, function(status, vals) {
        if (status == 1) {
            let selectTime = moment().format('YYYY-MM-DD').toString();
            let resdata = []
            if (data.Valid == 1) {
                resdata = vals
            } else {
                if (data.Valid == 99) {
                    for (let i = 0; i < vals.length; i++) {
                        if ((new Date(vals[i].EndTime.replace(/-/g, "\/"))) < (new Date(selectTime.replace(/-/g, "\/")))) {
                            resdata.push(vals[i])
                        }
                    }
                } else {
                    for (let j = 0; j < vals.length; j++) {

                        if ((new Date(vals[j].EndTime.replace(/-/g, "\/"))) >= (new Date(selectTime.replace(/-/g, "\/")))) {
                            resdata.push(vals[j])
                        }
                    }
                }
            }
            res.send({ status: status, data: resdata });
        } else {
            res.send({ status: status, err: vals });
        }

    });
});

// 搜索班级 class/search?searchText=&n=&m=&FK_UserGuid=
router.get('/search', function(req, res, next) {
    let data = {
        n: req.query.index || 0,
        m: req.query.num || 100000,
        searchText: '%' + req.query.searchText + '%'
    }
    ClassModel.search(data, function(status, result) {
        if (status) {
            let data = [];
            let selectTime = moment().format('YYYY-MM-DD').toString();
            http.get(`http://clientaccountserver.lessonplan.cn/user/joined/${req.query.FK_UserGuid}`, (re) => { //改
                let html = '';
                re.on('data', function(data) {
                    html += data;
                }).on('end', function(re2) {
                    html = JSON.parse(html);
                    for (let m = 0; m < result.length; m++) {
                        result[m].InvitationCode = null
                        if ((new Date(result[m].EndTime.replace(/-/g, "\/"))) >= (new Date(selectTime.replace(/-/g, "\/")))) {
                            data.push(result[m])
                        }
                    }
                    for (let i = 0; i < data.length; i++) {
                        data[i].joined = false
                        for (let j = 0; j < html.data.length; j++) {
                            if (data[i].PK_ClassGuid == html.data[j].FK_ClassGuid) {
                                data[i].joined = true
                            }
                        }
                    }
                    res.send({ status: status, data: data });
                });
            })
        } else res.send({ status: status, err: result });
    });
});



// 加入班级
router.post('/join', function(req, res, next) {

    ClassModel.join(req.body, function(status, vals) {
        if (status) res.send({ status: status, data: vals });
        else res.send({ status: status, err: vals });
    });
});
// 加入班级
router.post('/join2', function(req, res, next) {
    ClassModel.join2(req.body, function(status, vals) {
        if (status) res.send({ status: status, data: vals });
        else res.send({ status: status, err: vals });
    });
});
module.exports = router;